package com.file.system.controller.system;


import com.alibaba.excel.EasyExcel;
import com.file.system.entity.business.BusUtensilIndent;
import com.file.system.entity.business.BusUtensilIndentListener;
import com.file.system.entity.listener.CustomEvent;
import com.file.system.entity.listener.CustomEvent1;
import com.file.system.entity.res.CommonResult;
import com.file.system.plugin.file.FileTool;
import com.file.system.service.system.IWebFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.core.io.ResourceLoader;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;


/**
 * 系统测试类
 *
 * @author jch
 */
@RestController
@Validated
@RequestMapping("/test")
public class TestController {

    @Autowired
    private IWebFileService iWebFileService;
    @Autowired
    private ResourceLoader resourceLoader;
    @Autowired
    private FileTool fileTool;
    @Autowired
    private ApplicationContext applicationContext;


    @GetMapping("/file")
    public CommonResult file() {
        System.out.println("事件开始发布消息：" + System.currentTimeMillis());
        applicationContext.publishEvent(new CustomEvent(this, "你好啊"));

        return CommonResult.ok();
    }


    @GetMapping("/file1")
    public CommonResult file1() {
        System.out.println("事件开始发布消息：" + System.currentTimeMillis());
        applicationContext.publishEvent(new CustomEvent1(this, "你好啊22222"));

        return CommonResult.ok();
    }


    @GetMapping("/file2")
    public CommonResult file2() {
        String fileName = "D:/Desktop/1/快捷报表.xls";
        try {
            // 这里 需要指定读用哪个class去读，然后读取第一个sheet 文件流会自动关闭
            EasyExcel.read(fileName, BusUtensilIndent.class, new BusUtensilIndentListener()).sheet().doRead();
            return CommonResult.ok();
        } catch (Exception e) {
            e.printStackTrace();
            EasyExcel.read(rename(), BusUtensilIndent.class, new BusUtensilIndentListener()).sheet().doRead();
            return CommonResult.fail();
        }
    }

    private String rename(){
        String filePath = "D:/Desktop/1/快捷报表.xls";
        String newFilePath = "D:/Desktop/1/快捷报表.xlsx";

        File oldFile = new File(filePath);
        File newFile = new File(newFilePath);

        boolean isRenamed = oldFile.renameTo(newFile);

        if (isRenamed) {
            System.out.println("文件重命名成功。");
        } else {
            System.out.println("文件重命名失败。");
        }
        return newFilePath;
    }

}

